package ACWing.SearchAndGraphTheory.BFS;
//847. 图中点的层次
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;

/**
 * @author :chenjie
 * @date :Created 2022/12/25 20:39
 */
public class TheHierarchyOFPointsINTheGraph {
    static int n,m,idx;
    static class Pall{
        int i;
        int l;

        public Pall(int i, int l) {
            this.i = i;
            this.l = l;
        }
    }
    static int[]e=new int[100010];
    static int[]ne=new int[100010];
    static int[]h=new int[100010];
    static boolean[]st=new boolean[100010];
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        m=sc.nextInt();
        Arrays.fill(h,-1);
        for (int i = 0; i < m; i++) {
            int x=sc.nextInt();
            int y=sc.nextInt();
            add(x,y);
        }
        System.out.println(bfs());

    }
    public static void add(int a,int b){
        e[idx]=b;
        ne[idx]=h[a];
        h[a]=idx++;
    }
    public static int bfs(){
        Queue<Pall> queue=new ArrayDeque<>();
        queue.add(new Pall(1,0));
        st[1]=true;
        while (!queue.isEmpty()){
            Pall p = queue.remove();
            if(p.i==n){//尽可能将弹出条件放外面这样可以防止1就是n这个情况
                return p.l;
            }
            for (int i = h[p.i]; i != -1; i=ne[i]) {
                int j=e[i];
                if(!st[j]){
                    st[j]=true;

                    queue.add(new Pall(j,p.l+1));
                }
            }
        }
        return -1;
    }
}
